package com.goomba.demo.producer;

import com.goomba.demo.contants.Commons;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.nio.charset.StandardCharsets;

/**
 * 同步发送一些基本的信息
 */
public class SyncProducer {


    public static void main(String[] args) throws Exception {

        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("sync_producer_unique");

        defaultMQProducer.setNamesrvAddr(Commons.nameSrvAddr);

        defaultMQProducer.start();

        defaultMQProducer.setSendMsgTimeout(15000);


        // 中间部分是消息的发送

        for (int i = 0; i < 100; i++) {
            sendMessage(defaultMQProducer, i);
        }

        defaultMQProducer.shutdown();

    }

    private static void sendMessage(DefaultMQProducer defaultMQProducer, int index) throws Exception {

        byte[] body = ("test send message for " + index).getBytes(RemotingHelper.DEFAULT_CHARSET);
        // topic tag body
        Message message = new Message("TEST_TOPIC", "TEST_TAG", body);

        SendResult sendResult = defaultMQProducer.send(message); // 开始发送信息

        System.out.println(String.format("返回的数据是 %s", sendResult.toString()));
    }


}
